import React from 'react';
import {connect} from 'dva';
import {
  Table,
  Row,
  Col,
  Form,
  Input,
  Radio,
  DatePicker,
  Select,
  Upload,
  Button,
  Switch,
  Modal,
  Popconfirm,
  Tabs,
  message
} from 'antd';

const R = require('ramda');
import moment from 'moment'

const dateFormat = 'YYYY-MM-DD';
const {RangePicker} = DatePicker;
import Constants from "../../../utils/Constants";
import BizParams from "../../../components/commons/BizParams";
import SingleDragger from "../../../components/commons/SingleDragger";
import RightConstants from "../../../utils/RightConstants";
import RightBox from "../../../components/commons/RightBox";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

export default connect(({declareApproval}) => ({declareApproval}))(
  Form.create()(class invoice extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        open: false,
        type: null,
        id: null,
        tariffBill: ""
      }
    }

    componentDidMount() {
      this.props.dispatch({type: 'declareApproval/queryOrderManageList', payload: {invoiceStatus: "0"}});//查询订单列表
    }


    handleCancel = () => {
      this.setState({open: false, type: null, id: null});
      this.props.form.resetFields();

    }


    handleOpen = (record, type) => {
      this.setState({open: true, id: record.id, type});
    }

    handleSearch = (flag) => {
      let values = this.props.form.getFieldsValue();
      let newPage = this.props.declareApproval.page;
      newPage.page = flag ? newPage.page : 1;
      let form = {...R.omit(['onSuccess', 'onFail', 'status'])(values)};

      this.props.dispatch({
        type: 'declareApproval/queryOrderManageList',
        payload: {
          ...form,
          beginTime: values.submitTime && values.submitTime.length > 0 ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
          endTime: values.submitTime && values.submitTime.length > 1 ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
          page: newPage,
        }
      });

    };

    handleSubmit = () => {
      if (this.state.type === "upload" && this.refs.tariffBill.getUrl() == "") {
        message.error("请上传关税单!");
        return;
      }

      this.props.form.validateFields((errors, values) => {
        if (errors) return;

        let form = {};
        form.id = this.state.id;
        if (this.state.type === "edit") {
          form.invoiceStatus = values.status;
        } else {
          form.tariffBill = R.isNil(this.refs.tariffBill.getUrl()) ? '' : this.refs.tariffBill.getUrl();
        }

        this.props.dispatch({
          type: 'declareApproval/updateOrder',
          payload: {
            dataSource: form,
            onSuccess: () => {
              this.handleCancel();
              this.handleSearch();
            }
          },
        });

      });

    }


    columns = [
      {title: '客户名称', dataIndex: 'companyname', key: 'companyname'},
      {title: '订单编号', dataIndex: 'orderno', key: 'orderno'},
      {title: '合同协议号', dataIndex: 'contractno', key: 'contractno'},
      {title: '总货值', dataIndex: 'totalamount', key: 'totalamount'},
      {title: '币种', dataIndex: 'currencytype', key: 'currencytype'},
      {title: '手续费', dataIndex: 'agencyFee', key: 'agencyFee'},
      {title: '出口时间', dataIndex: 'exporttime', key: 'exporttime'},
      {title: '放行时间', dataIndex: 'passtime', key: 'passtime'},
      {title: '结关时间', dataIndex: 'finishtime', key: 'finishtime'},
      {
        title: '关税单', dataIndex: 'tariffBill', key: 'tariffBill',
        render: (text, record, index) => {
          let Link = "";

          if (record.tariffBill) {
            const defaultDownActionPre = apiPath.imagent + "/api/file/";
            const defaultDownActionSuf = "/download?fileName=";
            let fileName = encodeURI(encodeURI(record.tariffBill.substring(record.tariffBill.lastIndexOf('/') + 1, record.tariffBill.length)));
            let modules = "order";
            let downurl = defaultDownActionPre + modules + defaultDownActionSuf + fileName + "&" + Constants.ACJSESSIONID + "=" + sessionStorage.getItem(Constants.ACJSESSIONID);

            Link = <RightBox resource={RightConstants.CAPITAL.CAPITAL_RECREIPTS_DOWNLOAD} split={true}>
              <a href={downurl}>下载税单</a>
            </RightBox>
          }

          return <span>{Link}</span>;
        }
      },
      {
        title: '操作', width: '200px', fixed: 'right', key: 'key_oprator',

        render: (text, record, index) => {
          let preInvoice = <RightBox resource={RightConstants.CAPITAL.INVOICE_INFORMATION_EDIT} >
            <span><a href="#" onClick={() => this.handleOpen(record, "edit")}>编辑</a>   <span
              className="ant-divider"/></span>
          </RightBox>

          let preInvoiceDetail =
            <RightBox resource={RightConstants.CAPITAL.CAPITAL_RECREIPTS_UPLOAD}
                      // split={true}
            >
              <a href="#" onClick={() => this.handleOpen(record, "upload")}>上传税单</a>
            </RightBox>


          return (
            <span>
                                {record.invoiceStatus != "1" ? preInvoice : ""}
              {preInvoiceDetail}
                            </span>
          );

        }
      }
    ];

    render() {

      let formItemLayout = {labelCol: {span: 6}, wrapperCol: {span: 18}};
      const {getFieldDecorator} = this.props.form;
      let values = this.props.form.getFieldsValue();
      let form = {...R.omit(['onSuccess', 'onFail', 'status'])(values)};
      let pagination = {
        showTotal: total => `共 ${total} 条数据`,
        pageSize: this.props.declareApproval.page.size,
        total: this.props.declareApproval.page.totalRow,
        showSizeChanger: true,
        current: this.props.declareApproval.page.page,
        onShowSizeChange: (current, size) => {
          let newPage = this.props.declareApproval.page;
          newPage.size = size;
          newPage.page = 1;
          this.props.dispatch({
            type: 'declareApproval/queryOrderManageList',
            payload: {
              ...form,
              beginTime: values.submitTime && values.submitTime.length > 0 ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
              endTime: values.submitTime && values.submitTime.length > 1 ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
              page: newPage,
            }
          });
        },
        onChange: (pageNumber, pageSize) => {
          let newPage = this.props.declareApproval.page;
          newPage.page = pageNumber;
          this.props.dispatch({
            type: 'declareApproval/queryOrderManageList',
            payload: {
              ...form,
              beginTime: values.submitTime && values.submitTime.length > 0 ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
              endTime: values.submitTime && values.submitTime.length > 1 ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
              page: newPage,
            }
          });
        }
      }

      let footer = [
        <Button key="save" type="primary" size="large" onClick={this.handleSubmit.bind(this)}>提交</Button>,
        <Button key="cancel" size="large" onClick={this.handleCancel.bind(this)}>取消</Button>
      ]

      let module = "order";

      return (
        <div>

          <Row>
            <Col span={6}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(
              <Input/>)}</FormItem></Col>
            <Col span={6}><FormItem {...formItemLayout} label={'订单编号'}>{getFieldDecorator('orderNo')(
              <Input/>)}</FormItem></Col>
          </Row>
          <Row>
            <Col span={6}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractNo')(
              <Input/>)}</FormItem></Col>
            <Col span={6}>
              <FormItem {...formItemLayout} label={'开票状态'}>
                {getFieldDecorator('invoiceStatus', {
                  initialValue: '0'
                })(
                  <RadioGroup style={{width: 800}}>
                    <Radio value='0'>未开票</Radio>
                    <Radio value='1'>已开票</Radio>
                  </RadioGroup>
                )}
              </FormItem>
            </Col>
            <Col span={9} style={{float: 'left'}}>
              <Button type="primary" icon="search" style={{marginLeft: 35}}
                      onClick={this.handleSearch.bind(this)}>查询</Button>
            </Col>
          </Row>

          <Table rowKey="id" dataSource={this.props.declareApproval.list} columns={this.columns} bordered={true}
                 size={'middle'} pagination={pagination}/>

          <Modal maskClosable={false} footer={footer} visible={this.state.open} wrapClassName="vertical-center-modal"
                 title="开票资料" width="500" onCancel={this.handleCancel}>
            <Form>
              {this.state.type === "upload" ?
                <Row>
                  <Col span={20}>
                    <FormItem {...formItemLayout} label={<span className="ant-form-item-required">关税单</span>}
                              hasFeedback>
                      <SingleDragger url={R.isNil(this.state.tariffBill) ? '' : this.state.tariffBill.url}
                                     ref="tariffBill" module={module}/>
                    </FormItem>
                  </Col>
                </Row>
                :
                <Row>
                  <Col span={24}>
                    <FormItem
                      {...formItemLayout}
                      label="是否已开发票"
                      hasFeedback
                    >
                      {getFieldDecorator('status', {
                        rules: [{
                          required: true, message: '请选择是否已开发票！',
                        }],
                        initialValue: "0"
                      })(
                        <RadioGroup>
                          <Radio value={"1"}>是</Radio>
                          <Radio value={"0"}>否</Radio>
                        </RadioGroup>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              }

            </Form>
          </Modal>
        </div>
      )
    }
  })
)
